import 'package:sqflite/sqflite.dart';

import 'visitor_model.dart';

///来访事项表
String tableVisitMatter = "visitMatter";

///来访事项
String columnMatter = "matter";

///来访事项模型
class VisitMatter {
  String? matter;
  bool? selected;

  VisitMatter(this.matter, {this.selected = false});

  VisitMatter.forMap(Map<String, Object?> map) {
    matter = map[columnMatter] as String?;
    selected = false;
  }

  Map<String, Object?> toMap() {
    Map<String, Object?> map = {
      columnMatter: matter,
    };

    return map;
  }
}

class VisitMatterProvider {
  Database? db;

  Future open() async {
    db = await openDatabase(dbPath!);
  }

  Future close() async => db!.close();

  static final VisitMatterProvider _visitMatterProvider =
      VisitMatterProvider._internal();

  VisitMatterProvider._internal();

  factory VisitMatterProvider() {
    return _visitMatterProvider;
  }

  Future insert(VisitMatter visitMatter) async {
    await open();
    await db!.insert(tableVisitMatter, visitMatter.toMap());
    await close();
  }

  Future<int> delete(VisitMatter visitMatter) async {
    return await db!.delete(tableVisitMatter,
        where: "$columnMatter = ?", whereArgs: [visitMatter.matter]);
  }

  Future<List<VisitMatter>?> queryAll() async {
    await open();
    var maps = await db!.rawQuery("select * from $tableVisitMatter");

    if (maps.length > 0) {
      List<VisitMatter> allMatters = [];
      maps.forEach((element) {
        allMatters.add(VisitMatter.forMap(element));
      });
      await close();
      return allMatters;
    }
    await close();
    return null;
  }
}
